// backend/index.js

// --- 1. 导入依赖 ---
const express = require('express');
const cors = require('cors');
const db = require('./db'); // 这里连接数据库配置
const bcrypt = require('bcryptjs'); // 密码加密
const jwt = require('jsonwebtoken'); // 生成验证 Token
const authMiddleware = require('./middleware/auth'); // P3 新增: 身份验证中间件
// --- 2. 配置 ---
const app = express();
const PORT = 3000;
const JWT_SECRET = 'your_jwt_secret_key'; // 定义一个JWT密钥 (P2定义)

// --- 3. 中间件 ---
app.use(cors()); // 处理跨域请求
app.use(express.json()); // 解析请求中的 JSON 数据

// --- 4. API 路由 ---

// ---基础CRUD 1: 用户 Users表---

// C (Create): 用户注册
app.post('/api/register', async (req, res) => {
  try {
    const { username, password, email } = req.body;

    // 检查用户名是否已存在
    const [existingUsers] = await db.query('SELECT id FROM users WHERE username = ?', [username]);
    if (existingUsers.length > 0) {
      return res.status(400).json({ success: false, message: '用户名已存在' });
    }

    // (重要) 加密密码
    const hashedPassword = await bcrypt.hash(password, 10); // 10 是加密强度

    // 插入数据库
    const [result] = await db.query(
      'INSERT INTO users (username, password, email) VALUES (?, ?, ?)',
      [username, hashedPassword, email]
    );

    res.status(201).json({ success: true, message: '注册成功', userId: result.insertId });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// R (Read): 用户登录
app.post('/api/login', async (req, res) => {
  try {
    const { username, password } = req.body;

    // 1. 查找用户
    const [users] = await db.query('SELECT * FROM users WHERE username = ?', [username]);
    if (users.length === 0) {
      return res.status(401).json({ success: false, message: '用户名或密码错误' });
    }
    const user = users[0];

    // 2. 比较密码
    const isMatch = await bcrypt.compare(password, user.password);
    if (!isMatch) {
      return res.status(401).json({ success: false, message: '用户名或密码错误' });
    }

    // 3. (重要) 生成 JWT Token
    const tokenPayload = { id: user.id, username: user.username };
    const token = jwt.sign(tokenPayload, JWT_SECRET, { expiresIn: '1d' }); // Token 1 天过期

    // 4. 返回 Token 和用户信息 (去掉密码)
    delete user.password; 
    res.json({
      success: true,
      message: '登录成功',
      token: token,
      user: user
    });

  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// U (Update) 和 D (Delete) 将在 P3 或 P5 的 "个人中心" 模块实现


// ---基础CRUD 2: 电影 Movies表---

// R (Read): 获取所有电影列表
app.get('/api/movies', async (req, res) => {
  try {
    // P1 阶段的测试数据就在这里被获取
    const [movies] = await db.query('SELECT * FROM movies');
    res.json({ success: true, data: movies });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// R (Read): 获取单个电影详情 (动态路由)
app.get('/api/movie/:id', async (req, res) => {
  try {
    const { id } = req.params; // 获取 URL 中的 :id 参数
    
    // 1. 查找电影
    const [movie] = await db.query('SELECT * FROM movies WHERE id = ?', [id]);
    if (movie.length === 0) {
      return res.status(404).json({ success: false, message: '电影未找到' });
    }
    
    // (可选) 同时获取该电影的评论 (为 P3/P4 做准备)
    const [reviews] = await db.query(
        'SELECT r.*, u.username FROM reviews r JOIN users u ON r.user_id = u.id WHERE r.movie_id = ? ORDER BY r.created_at DESC', 
        [id]
    );

    res.json({ success: true, data: { ...movie[0], reviews } });

  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// C (Create): 添加电影 (通常是管理员操作, 将来实现完整的CRUD 2)
app.post('/api/movies', async (req, res) => {
    // (注意：这个接口需要管理员权限, P3/P5 加入鉴权中间件)
  try {
    const { title, director, actors, poster_image, description, release_date, duration_mins } = req.body;
    
    const [result] = await db.query(
      'INSERT INTO movies (title, director, actors, poster_image, description, release_date, duration_mins) VALUES (?, ?, ?, ?, ?, ?, ?)',
      [title, director, actors, poster_image, description, release_date, duration_mins]
    );
    
    res.status(201).json({ success: true, message: '电影添加成功', movieId: result.insertId });

  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// U (Update) 和 D (Delete) 电影 (管理员操作, P3/P5 可选实现)
// backend/index.js (粘贴在第 P2 个 API 之后)

// ---基础CRUD 3: 评论 Reviews表---

// C (Create): 添加评论 (需登录)
// P3 注意: 这个路由加中间件 authMiddleware
// 只有通过了 authMiddleware 验证 (即, 携带了有效 Token) 的用户才能访问
app.post('/api/review', authMiddleware, async (req, res) => {
  try {
    const { movie_id, rating, content } = req.body;

    // P3 注意: user_id 不再从 req.body 获取, 而是从 authMiddleware 添加的 req.user 中获取
    const user_id = req.user.id; 

    const [result] = await db.query(
      'INSERT INTO reviews (movie_id, user_id, rating, content) VALUES (?, ?, ?, ?)',
      [movie_id, user_id, rating, content]
    );

    // (可选增强) 添加评论后, 重新计算该电影平均分并更新到 movies 表
    // ...

    res.status(201).json({ success: true, message: '评论成功', reviewId: result.insertId });

  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// D (Delete): 删除评论 (需登录)
app.delete('/api/review/:id', authMiddleware, async (req, res) => {
  try {
    const { id } = req.params; // 要删除的评论ID
    const user_id = req.user.id; // 当前登录的用户ID

    // 删除时, 必须确保评论的拥有者本人才能删除
    const [result] = await db.query(
      'DELETE FROM reviews WHERE id = ? AND user_id = ?',
      [id, user_id]
    );

    if (result.affectedRows === 0) {
      // 没删除任何东西 (可能评论不存在, 或者该用户没有权限)
      return res.status(403).json({ success: false, message: '删除失败: 评论不存在或无权限' });
    }

    res.json({ success: true, message: '评论删除成功' });

  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});


// ---基础CRUD 5: 公告 Notices表---

// R (Read): 获取活跃公告列表 (公开接口，无需登录)
app.get('/api/notices', async (req, res) => {
  try {
    const now = new Date().toISOString().slice(0, 19).replace('T', ' ');
    
    // 查询活跃状态的公告，按优先级降序排列
    const [notices] = await db.query(`
      SELECT id, title, content, type, priority, start_time, end_time, created_at
      FROM notices 
      WHERE status = 'active' 
        AND start_time <= ?
        AND (end_time IS NULL OR end_time >= ?)
      ORDER BY priority DESC, created_at DESC
      LIMIT 10
    `, [now, now]);
    
    res.json({ success: true, data: notices });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// R (Read): 获取单个公告详情 (公开接口)
app.get('/api/notice/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const [notice] = await db.query(
      'SELECT id, title, content, type, priority, start_time, end_time, created_at FROM notices WHERE id = ? AND status = "active"',
      [id]
    );
    
    if (notice.length === 0) {
      return res.status(404).json({ success: false, message: '公告不存在或已下线' });
    }
    
    res.json({ success: true, data: notice[0] });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});


// ---基础CRUD 4: 订单 Orders表---

// C (Create): 创建订单 (需登录)
app.post('/api/orders', authMiddleware, async (req, res) => {
  try {
    const { movie_id, showtime, seat, price } = req.body;
    const user_id = req.user.id;

    // 生成一个简单的订单号
    const order_number = `MAOYAN_${Date.now()}_${user_id}`;

    const [result] = await db.query(
      'INSERT INTO orders (order_number, user_id, movie_id, showtime, seat, price, status) VALUES (?, ?, ?, ?, ?, ?, ?)',
      [order_number, user_id, movie_id, showtime, seat, price, 'confirmed']
    );

    res.status(201).json({ success: true, message: '购票成功', orderId: result.insertId, order_number });

  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// R (Read): 获取当前用户的订单列表 (需登录)
app.get('/api/orders', authMiddleware, async (req, res) => {
  try {
    const user_id = req.user.id;

    // P3 注意: 这里使用 JOIN 联表查询, 同时获取订单中的电影信息
    const [orders] = await db.query(
      `SELECT o.*, m.title AS movie_title, m.poster_image 
       FROM orders o
       JOIN movies m ON o.movie_id = m.id
       WHERE o.user_id = ?
       ORDER BY o.created_at DESC`,
      [user_id]
    );

    res.json({ success: true, data: orders });

  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// U (Update): 取消订单 (需登录)
app.put('/api/order/:id/cancel', authMiddleware, async (req, res) => {
  try {
    const { id } = req.params; // 订单ID
    const user_id = req.user.id; // 用户ID

    // 确保只有用户才能取消自己的订单
    const [result] = await db.query(
      "UPDATE orders SET status = 'cancelled' WHERE id = ? AND user_id = ?",
      [id, user_id]
    );

    if (result.affectedRows === 0) {
      return res.status(403).json({ success: false, message: '取消失败: 订单不存在或无权限' });
    }

    res.json({ success: true, message: '订单已取消' });

  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});


// ---管理员API接口---

// 获取所有电影 (管理员)
app.get('/api/admin/movies', async (req, res) => {
  try {
    const [movies] = await db.query('SELECT * FROM movies ORDER BY id DESC');
    res.json({ success: true, data: movies });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// 添加电影 (管理员)
app.post('/api/admin/movies', async (req, res) => {
  try {
    const { title, director, actors, poster_image, description, release_date, duration_mins, rating } = req.body;
    
    const [result] = await db.query(
      'INSERT INTO movies (title, director, actors, poster_image, description, release_date, duration_mins, rating) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
      [title, director, actors, poster_image, description, release_date, duration_mins, rating || 0.0]
    );
    
    res.status(201).json({ success: true, message: '电影添加成功', movieId: result.insertId });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// 更新电影 (管理员)
app.put('/api/admin/movies/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { title, director, actors, poster_image, description, release_date, duration_mins, rating } = req.body;
    
    const [result] = await db.query(
      'UPDATE movies SET title = ?, director = ?, actors = ?, poster_image = ?, description = ?, release_date = ?, duration_mins = ?, rating = ? WHERE id = ?',
      [title, director, actors, poster_image, description, release_date, duration_mins, rating, id]
    );
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ success: false, message: '电影不存在' });
    }
    
    res.json({ success: true, message: '电影更新成功' });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// 删除电影 (管理员)
app.delete('/api/admin/movies/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    // 先删除相关的评论和订单
    await db.query('DELETE FROM reviews WHERE movie_id = ?', [id]);
    await db.query('DELETE FROM orders WHERE movie_id = ?', [id]);
    
    // 再删除电影
    const [result] = await db.query('DELETE FROM movies WHERE id = ?', [id]);
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ success: false, message: '电影不存在' });
    }
    
    res.json({ success: true, message: '电影删除成功' });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// 获取所有评论 (管理员)
app.get('/api/admin/reviews', async (req, res) => {
  try {
    const [reviews] = await db.query(`
      SELECT r.*, u.username, m.title as movie_title 
      FROM reviews r 
      JOIN users u ON r.user_id = u.id 
      JOIN movies m ON r.movie_id = m.id 
      ORDER BY r.created_at DESC
    `);
    res.json({ success: true, data: reviews });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// 删除评论 (管理员)
app.delete('/api/admin/reviews/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const [result] = await db.query('DELETE FROM reviews WHERE id = ?', [id]);
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ success: false, message: '评论不存在' });
    }
    
    res.json({ success: true, message: '评论删除成功' });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// 获取所有订单 (管理员)
app.get('/api/admin/orders', async (req, res) => {
  try {
    const [orders] = await db.query(`
      SELECT o.*, u.username, m.title as movie_title 
      FROM orders o 
      JOIN users u ON o.user_id = u.id 
      JOIN movies m ON o.movie_id = m.id 
      ORDER BY o.created_at DESC
    `);
    res.json({ success: true, data: orders });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// 更新订单状态 (管理员)
app.put('/api/admin/orders/:id/status', async (req, res) => {
  try {
    const { id } = req.params;
    const { status } = req.body;
    
    const [result] = await db.query(
      'UPDATE orders SET status = ? WHERE id = ?',
      [status, id]
    );
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ success: false, message: '订单不存在' });
    }
    
    res.json({ success: true, message: '订单状态更新成功' });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// 删除订单 (管理员)
app.delete('/api/admin/orders/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const [result] = await db.query('DELETE FROM orders WHERE id = ?', [id]);
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ success: false, message: '订单不存在' });
    }
    
    res.json({ success: true, message: '订单删除成功' });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// 创建订单 (管理员)
app.post('/api/admin/orders', async (req, res) => {
  try {
    const { user_id, movie_id, showtime, seat, price, status } = req.body;

    // 生成订单号
    const order_number = `MAOYAN_${Date.now()}_${user_id}`;

    const [result] = await db.query(
      'INSERT INTO orders (order_number, user_id, movie_id, showtime, seat, price, status) VALUES (?, ?, ?, ?, ?, ?, ?)',
      [order_number, user_id, movie_id, showtime, seat, price, status || 'pending']
    );

    res.status(201).json({ success: true, message: '订单添加成功', orderId: result.insertId });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// 编辑订单 (管理员)
app.put('/api/admin/orders/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { user_id, movie_id, showtime, seat, price, status } = req.body;
    
    const [result] = await db.query(
      'UPDATE orders SET user_id = ?, movie_id = ?, showtime = ?, seat = ?, price = ?, status = ? WHERE id = ?',
      [user_id, movie_id, showtime, seat, price, status, id]
    );
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ success: false, message: '订单不存在' });
    }
    
    res.json({ success: true, message: '订单更新成功' });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// ---公告管理API接口 (管理员)---

// 获取所有公告 (管理员)
app.get('/api/admin/notices', async (req, res) => {
  try {
    const [notices] = await db.query('SELECT * FROM notices ORDER BY priority DESC, created_at DESC');
    res.json({ success: true, data: notices });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// 添加公告 (管理员)
app.post('/api/admin/notices', async (req, res) => {
  try {
    const { title, content, type, status, priority, start_time, end_time } = req.body;
    
    const [result] = await db.query(
      'INSERT INTO notices (title, content, type, status, priority, start_time, end_time) VALUES (?, ?, ?, ?, ?, ?, ?)',
      [title, content, type || 'normal', status || 'active', priority || 0, start_time, end_time]
    );
    
    res.status(201).json({ success: true, message: '公告添加成功', noticeId: result.insertId });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// 更新公告 (管理员)
app.put('/api/admin/notices/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { title, content, type, status, priority, start_time, end_time } = req.body;
    
    const [result] = await db.query(
      'UPDATE notices SET title = ?, content = ?, type = ?, status = ?, priority = ?, start_time = ?, end_time = ? WHERE id = ?',
      [title, content, type, status, priority, start_time, end_time, id]
    );
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ success: false, message: '公告不存在' });
    }
    
    res.json({ success: true, message: '公告更新成功' });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// 删除公告 (管理员)
app.delete('/api/admin/notices/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const [result] = await db.query('DELETE FROM notices WHERE id = ?', [id]);
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ success: false, message: '公告不存在' });
    }
    
    res.json({ success: true, message: '公告删除成功' });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// ---用户管理API接口---

// 获取所有用户 (管理员)
app.get('/api/admin/users', async (req, res) => {
  try {
    const [users] = await db.query('SELECT id, username, email, created_at FROM users ORDER BY id DESC');
    res.json({ success: true, data: users });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// 添加用户 (管理员)
app.post('/api/admin/users', async (req, res) => {
  try {
    const { username, password, email } = req.body;

    // 检查用户名是否已存在
    const [existingUsers] = await db.query('SELECT id FROM users WHERE username = ?', [username]);
    if (existingUsers.length > 0) {
      return res.status(400).json({ success: false, message: '用户名已存在' });
    }

    // 加密密码
    const hashedPassword = await bcrypt.hash(password, 10);

    // 插入数据库
    const [result] = await db.query(
      'INSERT INTO users (username, password, email) VALUES (?, ?, ?)',
      [username, hashedPassword, email]
    );

    res.status(201).json({ success: true, message: '用户添加成功', userId: result.insertId });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// 更新用户信息 (管理员)
app.put('/api/admin/users/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { username, email, password } = req.body;
    
    let updateQuery = 'UPDATE users SET username = ?, email = ?';
    let params = [username, email];
    
    // 如果提供密码，则更新密码
    if (password && password.trim() !== '') {
      const hashedPassword = await bcrypt.hash(password, 10);
      updateQuery += ', password = ?';
      params.push(hashedPassword);
    }
    
    updateQuery += ' WHERE id = ?';
    params.push(id);
    
    const [result] = await db.query(updateQuery, params);
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ success: false, message: '用户不存在' });
    }
    
    res.json({ success: true, message: '用户信息更新成功' });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// 删除用户 (管理员)
app.delete('/api/admin/users/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    // 先删除用户相关的评论和订单
    await db.query('DELETE FROM reviews WHERE user_id = ?', [id]);
    await db.query('DELETE FROM orders WHERE user_id = ?', [id]);
    
    // 再删除用户
    const [result] = await db.query('DELETE FROM users WHERE id = ?', [id]);
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ success: false, message: '用户不存在' });
    }
    
    res.json({ success: true, message: '用户删除成功' });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// 搜索用户 (管理员)
app.get('/api/admin/users/search', async (req, res) => {
  try {
    const { query } = req.query;
    
    if (!query) {
      return res.status(400).json({ success: false, message: '请提供搜索条件' });
    }
    
    const [users] = await db.query(
      'SELECT id, username, email, created_at FROM users WHERE username LIKE ? OR email LIKE ? ORDER BY id DESC',
      [`%${query}%`, `%${query}%`]
    );
    
    res.json({ success: true, data: users });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// --- 5. 启动服务器 ---
app.listen(PORT, () => {
  console.log(`后端服务器已启动，访问地址：http://localhost:${PORT}`);
});